<template>

	<view class="content">
		<view class="logo">
			<image class="logoImg" src="/static/logo.png" alt="" />
			</image>
		</view>
		<view class="login">
			<u-form :borderBottom='true' labelWidth='60' :model="form" ref="uForm" :error-type="'message'">
				<u-form-item :borderBottom='true' label="帐号:" prop="account">
					<u-input v-model="form.account" placeholder="请输入账号" />
				</u-form-item>
				<u-form-item :borderBottom='true' label="密码:" prop="password">
					<u-input type="password" v-model="form.password" placeholder="请输入密码" />
				</u-form-item>
			</u-form>
		</view>
		<view style="margin: 1rem 2rem;">
			<u-button @click="submit" type="primary">登录</u-button>
			<!-- <view class="forgetPassword" @click="forgetPassWord">忘记密码</view> -->
			<!-- <view class="reg" @click="register">注册</view> -->
		</view>

		<view class="bottonInfo">
			<u--text text="登录即代表同意"></u--text>
			<u--text @click="viewPage('privacyPolicy')" type="primary" text="《用户协议》"></u--text>
			<u--text @click="viewPage('serviceAgreement')" type="primary" text="《隐私政策》"></u--text>
		</view>

		<u-action-sheet :round='10' :show="showPage" :title="pageData.title" @close="()=>{showPage=false;}">
			<slot>
				<view style="max-height: 70vh; overflow-y: auto; text-align: left;">
				<view style="padding: 10px;" v-html="pageData.detail"></view>
				</view>
			</slot>
		</u-action-sheet>
	</view>
</template>

<script>
	import jsencrypt from "jsencrypt"
	import {
		toast,
		clearStorageSync,
		setStorageSync,
		getStorageSync,
		useRouter
	} from '@/utils/utils.js'

	export default {
		data() {
			return {
				baseInfo: {},
				form: {
					account: '',
					password: '',
				},
				publicKey: '',
				rules: {
					account: [{
						required: true,
						message: '请输入帐号',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}],
					password: [{
						required: true,
						message: '请输入密码',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}]
				},
				showPage: false,
				pageData: {}
			};
		},
		methods: {
			getLoginInfo() {
				this.$api.loginInfo().then(async res => {
					console.log('loginInfo', res)
					if (res.success) {
						let data = res.result || {}
						this.baseInfo = data.projectInfo || {}
						let systemSetting = data.systemSetting || {}
						this.baseInfo.loginTheme = systemSetting.loginTheme || 'blue'
						this.baseInfo.captchaEnable = systemSetting.captchaEnable == undefined ? false : systemSetting
							.captchaEnable
						this.baseInfo.encryptPassword = systemSetting.encryptPassword == undefined ? true : systemSetting
							.encryptPassword
						this.supportPathConfig = data.supportPathConfig || {}
						this.publicKey = data.publicKey
						setStorageSync('publicKey', this.publicKey)
						setStorageSync('systemSupport', data.supportPathConfig || {})
						// await this.$store.dispatch("updatePublicKey", this.publicKey)
						// await this.$store.dispatch("updateSystemSupport", data.supportPathConfig || {})
					} else {
						toast(res.msg)
					}
				})
			},
			submit() {
				this.$refs.uForm.validate().then(async res => {
					if (res) {
						console.debug("login valid", res)

						uni.showLoading({
							title: '登录中',
							mask: true
						})

						let data = {
							'account': this.form.account,
							'needCaptcha': false
						}
						if (this.baseInfo.encryptPassword) {
							var encrypt = new jsencrypt()
							encrypt.setPublicKey(this.publicKey)
							let encrypted = encrypt.encrypt(this.form.password)
							encrypted = encrypted.replace(/\+/g, '%2B')
							data.password = encrypted
						} else {
							data.password = this.form.password
						}
						this.$api.login(data).then(async res => {
							console.log(res)
							if (res.success) {
								toast(res.message || '登录成功')
								let data = res.result || {}
								let userInfo = data.userInfo || {}
								userInfo.accountType = data.accountType
								userInfo.userAccount = userInfo.account
								userInfo.pw = null
								// await this.$store.dispatch("updateUserInfo", Object.assign({}, userInfo))
								// await this.$store.dispatch("updateLawyerStatus", {})
								setStorageSync('userInfo', Object.assign({}, userInfo))
								setStorageSync('lawyerInfo', data.lawyerInfo || {})
								setStorageSync('lawFirmInfo', data.lawFirmInfo || {})
								setStorageSync('systemRoles', data.systemRoles || [])
								setStorageSync('lawyerStatus', {})
								setStorageSync(this.$systemConfig.token, res.result.sessionId)

								uni.$emit('initIM')

								useRouter('/pages/home/index', {}, 'switchTab')
							} else {
								toast(res.message)
							}
						}).finally(() => {
							uni.hideLoading()
						})
					} else {
						console.log('验证失败');
					}
				}).catch(e => {
					//TODO handle the exception
					console.error("doLogin validate error", e)
				})
			},
			register() {
				useRouter('/pages/login/register')
			},
			forgetPassWord() {
				useRouter('/pages/login/forget_password')
			},
			viewPage: function(type) {
				this.$api.page({
					pageType: type
				}).then(res => {
					if (res.success) {
						this.pageData = (res.result || {}).data || {}
						this.showPage = true
					} else {
						toast(res.message)
					}
				}).catch((err) => {
					console.log('err', err)
					toast('获取失败！')
				})
			}
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onLoad: function() {
			this.$store.dispatch('resetAll')
			this.getLoginInfo()
		},
		// #ifdef MP
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		}
		// #endif
		// #ifndef MP
		mounted() {
			this.$refs.uForm.setRules(this.rules);
		}
		// #endif
	};
</script>
<style lang="scss" scoped>
	.content {
		background-color: #fff;
		width: 100%;
		background-image: url('/static/images/login_bg.png');
		background-size: contain;
		background-repeat: no-repeat;
		background-position: left top;


		.logo {
			width: 150rpx;
			margin: 0 auto;
			padding-top: 140rpx;


		}

		.logoImg {
			width: 150rpx;
			height: 150rpx;
			background: $uni-bg-color;
			border-radius: 10px;
		}

		.login {
			width: 80%;
			margin: 0 auto;
			margin-top: 6rem;
		}

		.title {
			text-align: center;
			margin: 80rpx 0 0 0;
		}

		.reg {
			float: right;
			padding: 30rpx 0 30rpx 0;
			color: #2979ff;
			font-size: 14px;
		}

		.forgetPassword {
			float: left;
			padding: 30rpx 0 30rpx 0;
			color: #2979ff;
		}

		.bottonInfo {
			position: absolute;
			bottom: 0;
			text-align: center;
			white-space: nowrap;
			display: flex;
			justify-content: center;
			margin: auto;
			left: 0;
			right: 0;
			max-width: fit-content;
			padding: 6px 0;
		}
	}
</style>